package com.zkx.service;

import com.zkx.bean.User;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zkx
 */
//银行服务逻辑
public class BankService {

    private UserService userService = new UserService();

    //所有账户
    private Map<Integer,User> users = new HashMap<Integer,User>();

    //登入账户
    private User user;


    /**
     * 登入逻辑,
     * @return 返回对象
     */
    public User login(Integer id,String password) throws IOException, ClassNotFoundException {
        users = userService.getUser();
        this.user = users.get(id);
        if(this.user !=null && this.user.getPassword().equals(password)){
            //登入成功
            return this.user;
        }
        return null;
    }
    /**
     * 注册账户
     */
    public boolean register(User user) throws IOException, ClassNotFoundException {
        users = userService.getUser();
        //id冲突，不能注册
        if(users.get(user.getId())!=null){
            return false;
        }
        userService.addUser(users,user);
        return true;
    }
    /**
     * 注册账号，id不能冲突
     */
    public boolean checkId(Integer id){

        return users.get(id) == null ? true : false;
    }
    /**
     * 存钱取钱业务
     * 得到业务
     */
    public boolean saveMoney(double saveSumMoney){
        //存钱不能为空
        if(saveSumMoney < 0){
            return false;
        }
        double money = user.getMoney();
        user.setMoney(money + saveSumMoney);
        //更新信息
        users.replace(user.getId(),user);
        return true;
    }
    /**
     * 取钱
     */
    public boolean withdrawMoney(double saveSumMoney){

        double money = user.getMoney();

        //取钱不能大于余额
        if(saveSumMoney > money){
            return false;
        }
        user.setMoney(money - saveSumMoney);
        //更新信息
        users.replace(user.getId(),user);
        return true;
    }
    /**
     * 退出程序
     */
    public void exit() throws IOException {
        //退出将信息再次写进文件存储
        userService.saveUser(users);
    }
}
